package com.hugh.glrpcprovider.config;

import com.alibaba.fastjson.JSON;
import com.hugh.commom.zk.client.ZkConfigHandle;
import com.hugh.commom.zk.client.ZkRpcHandle;
import com.hugh.commom.zk.client.entity.ZkDataConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Author: Hugh
 * @Date: 2020/6/25
 */
@Component
@Slf4j
public class DataBaseConfig implements ApplicationListener<ContextRefreshedEvent> {

    private ZkDataConfig zkDataConfig;

    private ApplicationContext applicationContext;

    @Autowired
    private ZkConfigHandle zkConfigHandle;

        @SneakyThrows
        @Override
        public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
            ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
            HikariDataSource oldDataSource = (HikariDataSource)applicationContext.getBean("dataSource");
            applicationContext.getAutowireCapableBeanFactory().destroyBean(oldDataSource);
            ZkDataConfig dbConfig = zkConfigHandle.regist();
            HikariDataSource newdataSource = new HikariDataSource();
            newdataSource.setJdbcUrl(dbConfig.getUrl());
            newdataSource.setUsername(dbConfig.getUserName());
            newdataSource.setDriverClassName(dbConfig.getDriverClassName());
            newdataSource.setPassword(dbConfig.getPassWorld());
            log.info("替换引用:{}", JSON.toJSON(dbConfig));
            applicationContext.getAutowireCapableBeanFactory().configureBean(newdataSource, "dataSource");

        }

    public void updateDbConfig(ZkDataConfig newZkconfig){
        if(Objects.nonNull(applicationContext)){
            HikariDataSource oldDataSource = (HikariDataSource)applicationContext.getBean("dataSource");
            applicationContext.getAutowireCapableBeanFactory().destroyBean(oldDataSource);
            HikariDataSource newdataSource = new HikariDataSource();
            newdataSource.setJdbcUrl(newZkconfig.getUrl());
            newdataSource.setUsername(newZkconfig.getUserName());
            newdataSource.setDriverClassName(newZkconfig.getDriverClassName());
            newdataSource.setPassword(newZkconfig.getPassWorld());
            applicationContext.getAutowireCapableBeanFactory().configureBean(newdataSource, "dataSource");
            log.info("updateDbConfig done:{}",JSON.toJSON(newdataSource));
        }
    }
}
